﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace MisBasic.Service.Base
{
    /// <summary>
    /// MenuTree 的摘要说明
    /// </summary>
    public class MenuTree : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            Authorize authorize = new Authorize();
            String operator_id = authorize.GetLoginOperatorId(context);
            MisBasic.Dao.Base.RoleDao dao = new MisBasic.Dao.Base.RoleDao();
            String menuJson = GetMenuItem("0", false);
            context.Response.ContentType = "text/plain";
            context.Response.Write(menuJson.Substring(0, menuJson.Length - 2));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private String GetMenuItem(String pid, Boolean isChildren)
        {
            String menuJson = "";
            if (isChildren)
                menuJson += "\"children\":[";
            else
                menuJson += "[";
            MisBasic.Dao.Base.MenuDao dao = new MisBasic.Dao.Base.MenuDao();
            List<MisBasic.Domain.Base.Menu> menuList = dao.Get(new string[] { pid });
            foreach (MisBasic.Domain.Base.Menu menu in menuList)
            {
                List<MisBasic.Domain.Base.Menu> childMenuList = dao.Get(new string[] { menu.Id});
                menuJson += "{\"id\":\"" + menu.Id + "\",\"text\":\"" + menu.Text + "\",\"state\":\"open\",\"attributes\":{\"url\":\"" + menu.Url + "\"},";
                if (childMenuList.Count > 0)
                    menuJson += GetMenuItem(menu.Id, true);
                else
                    menuJson = menuJson.Substring(0, menuJson.Length - 1) + "},";
            }
            return menuJson.Substring(0, menuJson.Length - 1) + "]},";
        }
    }
}